<template>
  <div class="layout-manager">
    <el-card class="app-card">
      <template #header>
        <div class="card-header">
          <span>窗口布局管理</span>
        </div>
      </template>
      
      <el-tabs>
        <el-tab-pane label="自动排列">
          <div class="tab-content">
            <el-form label-position="top">
              <el-form-item label="屏幕选择">
                <el-select v-model="autoLayout.selectedScreen" placeholder="请选择屏幕">
                  <el-option 
                    v-for="screen in screens" 
                    :key="screen.id" 
                    :label="screen.primary ? '主屏幕' : `屏幕 ${screen.id}`" 
                    :value="screen.id" 
                  />
                </el-select>
              </el-form-item>
              
              <el-form-item label="排列方向">
                <el-radio-group v-model="autoLayout.direction">
                  <el-radio :label="'horizontal'">水平优先</el-radio>
                  <el-radio :label="'vertical'">垂直优先</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="窗口间距">
                <el-input-number 
                  v-model="autoLayout.margin" 
                  :min="0" 
                  :max="50" 
                  :step="5"
                />
              </el-form-item>
              
              <el-form-item>
                <el-button 
                  type="primary" 
                  :disabled="arranging" 
                  :loading="arranging" 
                  @click="autoArrange"
                >
                  <el-icon><i-ep-s-grid /></el-icon>
                  自动排列窗口
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="自定义排列">
          <div class="tab-content">
            <el-form label-position="top">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="起始X坐标">
                    <el-input-number v-model="customLayout.startX" :min="0" />
                  </el-form-item>
                </el-col>
                
                <el-col :span="12">
                  <el-form-item label="起始Y坐标">
                    <el-input-number v-model="customLayout.startY" :min="0" />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="窗口宽度">
                    <el-input-number v-model="customLayout.width" :min="100" />
                  </el-form-item>
                </el-col>
                
                <el-col :span="12">
                  <el-form-item label="窗口高度">
                    <el-input-number v-model="customLayout.height" :min="100" />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="水平间距">
                    <el-input-number v-model="customLayout.horizontalGap" :min="0" />
                  </el-form-item>
                </el-col>
                
                <el-col :span="12">
                  <el-form-item label="垂直间距">
                    <el-input-number v-model="customLayout.verticalGap" :min="0" />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="每行窗口数">
                    <el-input-number v-model="customLayout.perRow" :min="1" :max="10" />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-form-item>
                <el-button 
                  type="primary" 
                  :disabled="arranging" 
                  :loading="arranging" 
                  @click="customArrange"
                >
                  <el-icon><i-ep-s-operation /></el-icon>
                  自定义排列窗口
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Grid, Operation } from '@element-plus/icons-vue'

// 使用别名以避免命名冲突
const iEpSGrid = Grid
const iEpSOperation = Operation

interface Screen {
  id: number
  x: number
  y: number
  width: number
  height: number
  primary: boolean
}

const screens = ref<Screen[]>([])
const arranging = ref(false)

const autoLayout = reactive({
  selectedScreen: 0,
  direction: 'horizontal',
  margin: 10
})

const customLayout = reactive({
  startX: 0,
  startY: 0,
  width: 800,
  height: 600,
  horizontalGap: 10,
  verticalGap: 10,
  perRow: 2
})

// 获取屏幕信息
const loadScreens = async () => {
  try {
    const result = await window.electronAPI.getScreens()
    screens.value = result
    
    // 默认选择主屏幕
    const primaryScreen = result.find(s => s.primary)
    if (primaryScreen) {
      autoLayout.selectedScreen = primaryScreen.id
    }
  } catch (error) {
    console.error('获取屏幕信息失败:', error)
    ElMessage.error('获取屏幕信息失败')
  }
}

// 自动排列窗口
const autoArrange = async () => {
  if (arranging.value) return
  
  try {
    arranging.value = true
    
    // 获取运行中的窗口
    const runningWindows = await window.electronAPI.getRunningChromeWindows()
    
    console.log('获取到的运行中窗口:', runningWindows)
    
    if (runningWindows.length === 0) {
      ElMessage.warning('没有运行中的Chrome窗口可以排列')
      return
    }
    
    // 只选择有窗口句柄的窗口（正数ID）
    const validWindows = runningWindows.filter(w => w.id > 0)
    
    console.log('过滤后的有效窗口:', validWindows)
    console.log('窗口ID列表:', validWindows.map(w => w.id))
    
    if (validWindows.length === 0) {
      ElMessage.warning('没有可排列的窗口（所有运行中的Chrome都没有可见窗口）')
      return
    }
    
    console.log(`找到 ${validWindows.length} 个可排列的窗口:`, validWindows)
    
    const params = {
      type: 'auto',
      screenId: autoLayout.selectedScreen,
      direction: autoLayout.direction,
      margin: autoLayout.margin,
      windowIds: validWindows.map(w => w.id)
    }
    
    console.log('自动排列参数:', params)
    console.log('运行中的窗口:', runningWindows)
    
    const result = await window.electronAPI.arrangeWindows(params)
    
    if (result.success) {
      ElMessage.success(result.message || '窗口排列成功')
    } else {
      ElMessage.error(`窗口排列失败: ${result.error}`)
    }
  } catch (error) {
    console.error('自动排列窗口失败:', error)
    ElMessage.error('自动排列窗口失败')
  } finally {
    arranging.value = false
  }
}

// 自定义排列窗口
const customArrange = async () => {
  if (arranging.value) return
  
  try {
    arranging.value = true
    
    // 获取运行中的窗口
    const runningWindows = await window.electronAPI.getRunningChromeWindows()
    
    if (runningWindows.length === 0) {
      ElMessage.warning('没有运行中的Chrome窗口可以排列')
      return
    }
    
    // 只选择有窗口句柄的窗口（正数ID）
    const validWindows = runningWindows.filter(w => w.id > 0)
    
    if (validWindows.length === 0) {
      ElMessage.warning('没有可排列的窗口（所有运行中的Chrome都没有可见窗口）')
      return
    }
    
    console.log(`找到 ${validWindows.length} 个可排列的窗口:`, validWindows)
    
    const params = {
      type: 'custom',
      startX: customLayout.startX,
      startY: customLayout.startY,
      windowWidth: customLayout.width,
      windowHeight: customLayout.height,
      hSpacing: customLayout.horizontalGap,
      vSpacing: customLayout.verticalGap,
      windowsPerRow: customLayout.perRow,
      windowIds: validWindows.map(w => w.id)
    }
    
    console.log('自定义排列参数:', params)
    console.log('运行中的窗口:', runningWindows)
    
    const result = await window.electronAPI.arrangeWindows(params)
    
    if (result.success) {
      ElMessage.success(result.message || '窗口排列成功')
    } else {
      ElMessage.error(`窗口排列失败: ${result.error}`)
    }
  } catch (error) {
    console.error('自定义排列窗口失败:', error)
    ElMessage.error('自定义排列窗口失败')
  } finally {
    arranging.value = false
  }
}

onMounted(() => {
  loadScreens()
})
</script>

<style lang="scss" scoped>
.layout-manager {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .tab-content {
    padding: 20px 0;
  }
}
</style>